import { reqGetUserInfo, reqLogin, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  state() {
    return {
      token: getToken() || '',
      userInfo: {}
    }
  },
  mutations: {
    // 存token
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    // 存用户信息
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    // 清除token
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    // 清除用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 登录的请求
    async login(context, loginForm) {
      const res = await reqLogin(loginForm)
      console.log(res)
      const token = res.data
      context.commit('setToken', token)
    },
    // 获取用户基本资料
    async getUserInfo({ commit }) {
      const { data: data1 } = await reqGetUserInfo()
      // console.log(data)
      const { data: data2 } = await reqGetUserDetailById(data1.userId)
      const res = { ...data1, ...data2 }
      commit('setUserInfo', res)
      return res
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
    }
  },
  namespaced: true
}
